import React, { useState } from 'react';
import { Text, View, StyleSheet, Image, TextInput, TouchableOpacity, SafeAreaView, Alert, ActivityIndicator } from 'react-native';
import { adapt, adaptFontSize, getScreenWidth, getScreenHeight } from '../../ulits/Adapt';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { LoginAPI } from '../../ulits/instance';
import AsyncStorage from '@react-native-async-storage/async-storage';

type LoginProps = {
  navigation: NativeStackNavigationProp<any>;
};

export default function Login({ navigation }: LoginProps) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);

  const handleLogin = async () => {
    try {
      // 1. 输入验证
      if (!username.trim()) {
        Alert.alert('提示', '请输入用户名');
        return;
      }
      if (!password.trim()) {
        Alert.alert('提示', '请输入密码');
        return;
      }

      setLoading(true);
      console.log('开始登录请求:', { username: username.trim() });

      // 2. 发起登录请求
      const response = await LoginAPI({
        username: username.trim(),
        password: password.trim()
      });

      console.log('登录响应:', response);

      // 3. 处理响应
      if (response.setAccessToken && response.setRefreshToken) {
        // 令牌已在响应拦截器中保存
        if (response.user) {
          // 保存用户信息到本地存储
          try {
            await AsyncStorage.setItem('userData', JSON.stringify(response.user));
            console.log('用户数据保存成功');

            Alert.alert('登录成功', '欢迎回来', [
              {
                text: '确定',
                onPress: () => navigation.replace('MeTab')
              }
            ]);
          } catch (error) {
            console.error('保存用户数据失败:', error);
            Alert.alert('提示', '保存用户信息失败，请重试');
          }
        }
      } else {
        Alert.alert('提示', response.message || '登录失败，请检查用户名和密码');
      }
    } catch (error: any) {
      console.error('登录错误:', error);
      Alert.alert(
        '登录失败',
        error.message === '用户名或密码错误'
          ? '用户名或密码错误，请重试'
          : '网络连接失败，请检查网络设置'
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <Image
        source={require('./image/1.png')}
        style={styles.backgroundImage}
        resizeMode="cover"
      />

      <View style={styles.contentContainer}>
        <View style={styles.headerContainer}>
          <Text style={styles.title}>登录App</Text>
          <Text style={styles.subtitle}>开启属于你的畅聊之旅</Text>
        </View>

        <View style={styles.inputContainer}>
          <View style={styles.inputWrapper}>
            <Image source={require('./image/user.png')} style={styles.inputIcon} />
            <TextInput
              style={styles.input}
              placeholder="请输入用户名"
              placeholderTextColor="#999"
              value={username}
              onChangeText={setUsername}
              editable={!loading}
              autoCapitalize="none"
              autoCorrect={false}
            />
          </View>

          <View style={styles.inputWrapper}>
            <Image source={require('./image/lock.png')} style={styles.inputIcon} />
            <TextInput
              style={styles.input}
              placeholder="请输入密码"
              placeholderTextColor="#999"
              secureTextEntry
              value={password}
              onChangeText={setPassword}
              editable={!loading}
              autoCapitalize="none"
              autoCorrect={false}
            />
          </View>

          <TouchableOpacity
            style={[styles.loginButton, loading && styles.loginButtonDisabled]}
            onPress={handleLogin}
            disabled={loading}
          >
            {loading ? (
              <ActivityIndicator color="#fff" size="small" />
            ) : (
              <Text style={styles.loginButtonText}>登录</Text>
            )}
          </TouchableOpacity>

          <View style={styles.linkContainer}>
            <TouchableOpacity onPress={() => navigation.navigate('Phone')}>
              <Text style={styles.linkText}>注册账号</Text>
            </TouchableOpacity>
            <TouchableOpacity>
              <Text style={styles.linkText}>忘记密码</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.socialLoginContainer}>
          <Text style={styles.socialLoginText}>其它方式登录</Text>
          <View style={styles.socialIconsContainer}>
            <TouchableOpacity style={styles.socialIcon}>
              <Image source={require('./image/weixin.png')} style={styles.socialIconImage} />
            </TouchableOpacity>
            <TouchableOpacity style={styles.socialIcon}>
              <Image source={require('./image/qq.png')} style={styles.socialIconImage} />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.socialIcon}
              onPress={() => navigation.navigate('FaceLR')}
            >
              <Image source={require('./image/shouji.png')} style={styles.socialIconImage} />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.socialIcon}
              onPress={() => navigation.navigate('Face')}
            >
              <Image source={require('./image/mianbu.png')} style={styles.socialIconImage} />
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backgroundImage: {
    position: 'absolute',
    width: getScreenWidth(),
    height: getScreenHeight(),
  },
  contentContainer: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    padding: adapt(20),
  },
  headerContainer: {
    alignItems: 'center',
    marginTop: adapt(80),
  },
  title: {
    fontSize: adaptFontSize(28),
    fontWeight: 'bold',
    color: '#ffffff',
    marginBottom: adapt(8),
  },
  subtitle: {
    fontSize: adaptFontSize(20),
    color: '#ffffff',
    opacity: 0.8,
  },
  inputContainer: {
    marginTop: adapt(60),
    paddingHorizontal: adapt(20),
  },
  inputWrapper: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#ffffff',
    borderRadius: adapt(25),
    marginBottom: adapt(15),
    paddingHorizontal: adapt(15),
  },
  inputIcon: {
    width: adapt(20),
    height: adapt(20),
    marginRight: adapt(10),
  },
  input: {
    flex: 1,
    height: adapt(50),
    fontSize: adaptFontSize(16),
    color: '#333',
    padding: 0,
  },
  loginButton: {
    backgroundColor: '#FF9500',
    borderRadius: adapt(25),
    height: adapt(50),
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: adapt(10),
  },
  loginButtonDisabled: {
    opacity: 0.7,
  },
  loginButtonText: {
    color: '#ffffff',
    fontSize: adaptFontSize(18),
    fontWeight: 'bold',
  },
  linkContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: adapt(15),
    paddingHorizontal: adapt(10),
  },
  linkText: {
    color: '#ffffff',
    fontSize: adaptFontSize(14),
  },
  socialLoginContainer: {
    marginTop: 'auto',
    alignItems: 'center',
    paddingBottom: adapt(40),
  },
  socialLoginText: {
    color: '#ffffff',
    fontSize: adaptFontSize(14),
    marginBottom: adapt(20),
  },
  socialIconsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: '80%',
  },
  socialIcon: {
    width: adapt(44),
    height: adapt(44),
    borderRadius: adapt(22),
    backgroundColor: '#ffffff',
    justifyContent: 'center',
    alignItems: 'center',
  },
  socialIconImage: {
    width: adapt(30),
    height: adapt(30),
  },
});